// SlagCar/DailyCheckList/component/checkList.js
// 240117 yan 复制pages/general_entity/general_entity.js定制修改
let listBehavior = require('../../../behavior/list')
const req = require('../../../utils/request');
Component({

  behaviors: [ listBehavior, ],

  properties:{
    entity: {
      type: String,
    },
    type: {type:String}

  },

  /**
   * 页面的初始数据
   */
  data: {
    tableid: '', //模块id
    tableName: '',  //模块名
    searchPlc: '搜索',  //搜索占位文字
    list:[],  //显示数据

    fieldList: [], //所有字段列表

    displayField: [],  //显示字段列表

    keyList: [],  //搜索关键字
    searchList: [], //快速查询字段列表
    advList: [],  //高级查询列表

    sumList: [], //底部统计字段集合
    cashierBtn: false,


    baseFilter: [], //基础条件
    where: [],
    system_id: wx.getStorageSync('system_id') || 800,  //231215 yan 图片字段只返回文件名时，需要系统号拼接图片地址
    baseURL: req.baseURL
  },

  methods:{

    //获取数据
    getDataList(){
      let url = 'DynamicQuery/query_dynamic_v3',
        {tableid, where,page,limit,type} = this.data,
        post = {
        "table_id": tableid,
          // "oby": tableid + ".row_id desc",
          "oby": `charindex(isnull(${tableid}.jianchajieguo,'其它'),'其它正常隐患')`,
          page,limit};
      //240117 定制修改
      let filters = [];
      //240124 yan 基础条件 管理员端不需要，司机端需要过滤车牌号码为当前号码
      if (type === 'driver'){
        filters.push({"CompareWith":`${tableid}.chepaihaomayinyong`,"Operator":"=","CompareValue": this.data.driver_car_row_id,"or":0})
      }
      //240117 end

      if (where && where[0]){
        filters = [...filters,...where];
      }
      filters.length && (post.SearchWhere = {filters ,type: 'and'});
      wx.$post(3,url,post).then(res => {
        let total = 0,
          {list} = this.data,
          sumArr = [],
          obj = {};
        if (res.data.row){
          total = res.data.total;
          let rows = res.data.row;
          if(page !== 1) rows = [ ...list,...rows, ]
          obj = {total,list: rows,page};
        }
        sumArr.push({name: '记录数',num: total});
        if (res.data.sum && res.data.sum[0]) {
          wx.$each(res.data.sum[0],(key,val)=>{
            sumArr.push({name: key,num: wx.$util.formatNum(val)});
          })
        }
        obj.sumList = sumArr;
        this.setData(obj);
      });
    },

    //搜索
    searchData(e){
      this.data.where = e.detail.comb;

      this.getFirstPage();
    },
    //刷新列表
    refreshData(){
      this.getFirstPage();
    },

    //获取表信息
    getEntityParam(){
      let post = {}
      wx.$post(3,'Entity_param/query_entity_param',{table_id: this.data.tableid}).then(res=>{
        if (res.errcode != 0)return;
        this.setData({
          entityParam: res.data.row[0],
          tableName: res.data.row[0].table_name
        })
      })
    },
    //获取列显示--221109 yan 取消显示列显示
    getFieldDisplay(){
      let url = 'Entity_field_display/query_entity_field_display',
        entity = this.data.tableid,
        post = {
          "table_id": entity,
          "display_id": ''
        };
      wx.$post(3,url,post,false,true).then(res => {
        this.setData({
          displayField: res.showFields
        });

        this.getDataList();
      })
    },
    //获取列表页布局--221109 yan 获取列表页布局
    getListLayout(tableid){
      let url = 'Custom/get_html_WXMiniProgram',
        post = {'table_id': tableid};
      return new Promise(resolve => {
        wx.$post(1,url,post).then((res)=>{
          if (res.errcode != 0)return;
          let data = res.data.row && res.data.row[0],
            layout = data && data.html_js_query  || '';
          try {
            layout = JSON.parse(layout);
          }catch (e) {}

          resolve(layout);
        })

      })
    },


    // 接口
    ready() {
      let { tableid, } = this.data,
        p0 = this.getListLayout(tableid),
        p1 = this.getAllEntityFields(tableid),
        p2 = this.getQuickFilter(tableid)
      // 1.获取列表布局，2.获取所有字段 3.获取快速查询条件，3.1获取引用筛选的主显示字段，3.2获取引用筛选的选项，4.获取所有字段得到单选多选的选项，3.获取高级查询tab
      Promise.all([p0, p1, ]).then(res => {
        let layout = res[0],
          fieldList = res[1],
          displayField = [];

        wx.$each(layout,(i,item)=>{
          let field = fieldList.find(ite=>{
            return ite.field_id === item || ite.fieldName === item
          });
          field && displayField.push(field);
        });

        this.setData({
          displayField: displayField
        });
        this.getDataList();


        p2.then(res=>{
          let searchList = res,
            radioCheckList = {}
          fieldList.forEach(row => {
            let { type, field_id, } = row
            if(['picklist', 'multiple'].includes(type)) radioCheckList[field_id] = JSON.parse(row.option)
          })

          searchList && searchList.forEach(item => {
            let { type, field_id, } = item;
            if(['picklist', 'multiple', ].includes(type)) item.optionList = radioCheckList[field_id]
          // 240125 yan 定制检查时间input_time增加今天默认值
            if (field_id === 'input_time') item.dfltdate = 0
          // 240125 end
          })

          this.setData({
            searchList,
          })

          console.log(this.data.searchList);
        })
      })

      this.getAdvTab(tableid);
      this.getCashierEntity();
    },
    // 2.获取模块所有字段
    getAllEntityFields(tableid) {
      return new Promise((resolve, reject) => {
        wx.$post(4, 'QX/PRO_select_field', { table: tableid, fieldname: '', }).then(res => {
          if(res.errcode !== 0) return
          let rows = res.data.row;
          resolve(rows);
        })
      })
    },
    // 3.获取筛选条件项目
    getQuickFilter(tableid) {
      return new Promise((resolve, reject) => {
        wx.$post(3, 'Entity_query_model/query_entity_query_model', { table_id: tableid, }, '', true).then(res => {
          let { showFields, query_field, } = res,
            obj = {}

          this.setData({
            keyList: query_field,
          })

          showFields && showFields.forEach(item => {
            let { type, mainEntity, } = item
            if(['reference1', 'reference', ].includes(type)) {
              if(!obj[mainEntity]) obj[mainEntity] = []
              obj[mainEntity].push(item)
            }
          })
          let proArr = []
          Object.keys(obj).forEach(entity => {
            proArr.push(this.getRefOptionList(entity, obj[entity]))
          })

          Promise.all(proArr).then(res => {
            resolve(showFields)
          })
        })
      })
    },
    // 获取引用字段的选项
    getRefOptionList(tableid, arr) {
      return new Promise((resolve, reject) => {
        // 1.1获取模块的主显示字段
        let p0 = new Promise((resolve, reject) => {
          wx.$post(3, 'Entity_param/query_entity_param', { table_id: tableid, }).then(res => {
            if(res.errcode !== 0) return
            resolve(res.data.row[0].entity_key)
          })
        })
        // 1.2获取引用字段的选项
        let p1 = new Promise((resolve, reject) => {
          wx.$post(3, 'DynamicQuery/query_dynamic', { oby: `${tableid}.row_id desc`, table_id: tableid, }).then(res => {
            if(res.errcode !== 0) return
            resolve(res.data.row[0])
          })
        })

        Promise.all([p0, p1, ]).then(res => {
          let optionName = res[0],
            optionList = res[1]
          arr.forEach(item => {
            item.optionName = optionName
            item.optionList = optionList
          })
          resolve()
        })
      })
    },
    // 3.获取高级查询tab
    getAdvTab(tableid) {
      let post = {
        system_id: 800,
        page: 1,
        limit: 1000,
        oby: 'input_time',
        SearchWhere: [
          {
            CompareWith: 'table_id',
            Operator: '=',
            CompareValue: tableid,
            or: 0,
          },
        ],
      }
      wx.$post(3, 'DynamicQuery/query_personal_combination_query', post).then(res => {
        if(res.errcode !== 0) return
        this.setData({
          advList: res.data.row,
        })
      })
    },

    //获取出纳模块
    getCashierEntity () {
      let { tableid, } = this.data;
      wx.$post(1,'AllCashierEntity/select_all_cashier_entity',{table_id: tableid}).then(res=>{
        if (res.errcode != 0){return}
        let data = res.data.row || [];
        if (data && data.length > 0){
          this.setData({
            cashierEntity: data[0],
            cashierBtn: true})
        }
      })
    },

    //删除
    bindDelete(e){
      let data = e.currentTarget.dataset,
        rid = data.rid,
        index = data.index;
      if (!this.data.auth.tableDelete) {
        wx.$toast('抱歉，您没有权限删除该模块数据！');
        return
      }
      wx.showModal({
        title: '提示',
        content: '确认删除该记录？',
        success: (res) => {
          if(res.confirm) {
            wx.showLoading();
            this.deleteData(rid).then(()=>{
              let list = this.data.list;
              list.splice(index, 1);
              wx.$toast('删除成功！');
              this.setData({
                list
              });
            });
          }
        },
      })
    },
    //删除记录
    deleteData(rid){
      return new Promise(resolve => {
        wx.$post(3,'DynamicUpdate/dynamic_delete',{row_ids: rid.toString(),table_id: this.data.tableid}).then(res=>{
          if (res.errcode != 0)return;
          resolve();
        })
      })
    },
    //删除客户--客户表删除需要进行数据验证接口404
    deleteCustomer(rid){
      let url =  'DynamicUpdate/CheckCustomerBusiness?Id=' + rid.toString();
      wx.$post(3,url,null,true,true).then(async res=>{
        console.log(res);
        if (res.Code == 0){
          //删除操作

        } else {
          var msg = '';
          var code = parseInt(res.Code);
          while (code == -2) {
            sleep(500);
            url = 'DynamicUpdate/CheckCustomerBusiness?guid=' + res.GUID;
            await wx.$post(3,url,null,true,true).then(dt=>{

              code = parseInt(dt.Code);
              msg = dt.Msg;
              if (code == -2) {
                wx.$toast(dt.Speed);
              }
            });

          }
          if (code == 0){
            //删除操作

          } else {
            wx.$toast(msg);
          }
        }
      })
    },
    //跳转页面
    navTo(e){
      let {url,type} = e.currentTarget.dataset;
      if (type === 'add' && !this.data.auth.tableAppend) {
        wx.$toast('抱歉，您没有权限新增该模块数据！');
        return
      }
      wx.navigateTo({
        url: url
      })
    },

    // 预览图片
    previewImg(e) {
      let { index, urls, } = e.currentTarget.dataset;
      let {  system_id,baseURL } = this.data,
        uploadImgs = urls && urls.split(','),
        imgs = [];
      //231215 yan 修改 图片字段只返回文件名称，通过系统号拼接图片访问地址
      uploadImgs.forEach(item => {
        let name = item.substring(item.lastIndexOf('/')+1);
        imgs.push(`${baseURL}/files/${system_id}/${name}`)
      });
      //231215 end
      wx.previewImage({
        current: imgs[index],
        urls: imgs
      })
    },


  },

  // 生命周期
  lifetimes: {
    created() {},
    attached() {},
    ready() {
      let {entity} = this.data,
        obj = { driver_car_row_id: wx.getStorageSync('driver_car_row_id')};
      let where = wx.getStorageSync('echarts') || [];
      if (where.length){wx.removeStorageSync('echarts');}
      where = [...where,{CompareValue: 0, CompareWith: `DATEDIFF(day,${entity}.input_time,GETDATE())`, Operator: "=", or: 0}]
      obj.where = where;
      this.setData(obj);

      wx.$getAuth(entity).then(res=>{
        if (!res.tableSee) {
          wx.$toast('抱歉，您没有权限查看该模块数据！',1000).then(()=>{
            wx.navigateBack({ delta:1 });
          });
          return
        }
        this.setData({
          auth: res,
          tableid: entity
        });
        this.getEntityParam();
        this.ready();
      });
    },
    moved() {},
    detached() {},
    error() {},
  },

});
function sleep(n) {
  var start = new Date().getTime();
  while (true) {
    if (new Date().getTime() - start > n) {
      break;
    }
  }
}
